package com.yeziji.devops.sql.constructor;

import cn.hutool.core.util.StrUtil;
import com.yeziji.common.CommonSymbol;
import com.yeziji.constant.VariousStrPool;
import com.yeziji.devops.constant.SqlExecuteTypeEnum;
import com.yeziji.devops.constant.mysql.MysqlKeywordEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import javax.validation.constraints.Min;
import java.util.StringJoiner;

/**
 * 分页 SQL 构造器
 *
 * @author gzkemays
 * @since 2023/01/06 8:20 PM
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
@EqualsAndHashCode(callSuper = true)
public class PageSqlConstructor extends SelectSqlConstructor {
    /**
     * 页码
     */
    @Min(value = 0, message = "页码必须大于0")
    private int page;

    /**
     * 截取数据长度
     */
    private int limit;

    @Override
    protected void check() {
        super.check();
        if (!super.type.equals(SqlExecuteTypeEnum.SELECT.getValue())) {
            throw new IllegalArgumentException("分页只能用于查询");
        }
    }

    @Override
    public String buildSql() {
        this.check();
        return super.buildSql().replace(MysqlKeywordEnum.END.getValue(), VariousStrPool.EMPTY)
                + " limit "
                + this.page * this.limit
                + CommonSymbol.COMMA
                + this.limit
                + MysqlKeywordEnum.END.getValue();
    }

    /**
     * 构建主键 count(1)
     *
     * @return {@link String}
     */
    public String buildPrimaryCount() {
        return this.buildCount("1");
    }

    /**
     * 构建字段的 select count(x) from table
     *
     * @param column 字段信息
     * @return {@link String}
     */
    public String buildCount(String column) {
        super.check();

        StringJoiner sqlJoiner = new StringJoiner(CommonSymbol.SPACE, VariousStrPool.EMPTY, MysqlKeywordEnum.END.getValue());
        sqlJoiner.add(SqlExecuteTypeEnum.SELECT.getValue())
                .add(MysqlKeywordEnum.count(column))
                .add(MysqlKeywordEnum.FROM.getValue())
                .add(super.table);
        // fill wrapper
        if (StrUtil.isNotBlank(super.wrapper)) {
            sqlJoiner.add(MysqlKeywordEnum.WHERE.getValue()).add(super.wrapper);
        }
        return sqlJoiner.toString();
    }

    public static void main(String[] args) {
        PageSqlConstructor constructor =
                PageSqlConstructor.builder()
                        .type("select")
                        .table("yzj_forum")
                        .wrapper("username=gzkemays")
                        .page(1)
                        .limit(5)
                        .build();
        System.out.println("constructor = " + constructor.buildSql());
        System.out.println(constructor.buildPrimaryCount());
    }
}
